package com.martin.lib_base.model

import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.RecyclerView
import com.martin.lib_base.bean.BaseListBean
import com.martin.lib_base.interfaces.IAdapter
import com.martin.lib_base.interfaces.IGetData
import com.martin.lib_base.ktx.loadMore
import com.martin.lib_base.ktx.refresh
import com.scwang.smart.refresh.layout.SmartRefreshLayout

/**
 * @desc：分页用工具
 */
class PageModel {

    //页码
    var page: Int = 1

    /**
     * 最后一条ID
     */
    var lastId: Int = 0

    /**
     * 是否有更多数据
     * 用于决定刷新布局能否加载更多
     */
    val haveMore = MutableLiveData(false)

    /**
     * 是否处于加载中
     * 一般情况下,监听改变就关闭加载状态
     */
    val loadRefreshing = MutableLiveData(false)

    //列表布局
    private var rv: RecyclerView? = null

    /**
     * 刷新
     */
    fun refresh() {
        page = 1
        lastId = 0
        haveMore.postValue(false)
    }

    /**
     * 加载更多
     */
    fun loadMore() {
        page += 1
    }

    /**
     * 当前是否为刷新模式
     */
    fun isRefresh() = page == 1

    /**
     * 绑定刷新布局逻辑
     */
    fun bindSmartRefreshLayout(
        //刷新布局
        srl: SmartRefreshLayout,
        //列表布局
        rv: RecyclerView,
        //获取数据对象
        getData: IGetData,
        //生命周期持有者
        lifecycleOwner: LifecycleOwner
    ) {
        this.rv = rv
        srl.post {
            // 监听刷新事件
            srl.setOnRefreshListener {
                refresh()
                getData.getData()
            }
            // 监听加载更多
            srl.setOnLoadMoreListener {
                loadMore()
                getData.getData()
            }

            lifecycleOwner.let {
                //观察是否刷新完成
                loadRefreshing.observe(lifecycleOwner) {
                    srl.finishLoadMore()
                    srl.finishRefresh()
                }

                //观察是否可以加载更多数据
                haveMore.observe(lifecycleOwner) {
                    srl.setEnableLoadMore(it)
                }
            }
        }
    }

    /**
     * 处理列表数据
     */
    fun handleDataList(list: List<Any>?) {
        rv?.let {
            it.post {
                if (isRefresh()) {
                    it.refresh(list)
                } else {
                    it.loadMore(list)
                }
            }
        }
        // 关闭加载状态
        loadRefreshing.postValue(false)
    }

    /**
     * 处理listBean数据
     */
    fun handleListBean(listBean: BaseListBean<Any>) {
        lastId = listBean.lastId
        handleDataList(listBean.list)
        haveMore.postValue(listBean.currentPage < listBean.lastPage)
    }

}

